package edu.cebanc.spring.biblioteca.controllers;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.cebanc.spring.biblioteca.bean.UserBean;
import edu.cebanc.spring.biblioteca.services.UsersService;

@Controller
@RequestMapping(value="/users")
public class UserController {
	
	@Autowired
	UsersService usersService;

	@RequestMapping(method=RequestMethod.GET)
	public String getMainView(Model model) {
		model.addAttribute("user", usersService.listUsers());
		
		return "usersMain";
	}
	
	@RequestMapping(value="/usersForm", method=RequestMethod.GET)
	public String getFormView(Model model) {
		
		UserBean ub = new UserBean();
		model.addAttribute("user", ub);
		
		return "usersForm";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String getUsersData(@Valid UserBean ub, BindingResult result) {
		if(result.hasErrors()) {
			return "redirect:/users/usersForm";
		}
		usersService.saveUser(ub);
		
		return "redirect:/users";
	}
	
	@RequestMapping(value="/userInfo/{id}", method=RequestMethod.GET)
	public String getInfoView(@PathVariable String id, Model model) {
		model.addAttribute("user", usersService.loadUser(id));
		//System.out.println(usersService.loadUser(id).toString());
		return "userInfo";
	}

	@RequestMapping(value="/editUser/{id}", method=RequestMethod.GET)
	public String editUser(@PathVariable String id, Model model) {
		model.addAttribute("user", usersService.loadUser(id));
		
		return "usersForm";
	}
	
	@RequestMapping(value="/deleteUser/{id}", method=RequestMethod.GET)
	public String delete(@PathVariable String id) {
		usersService.deleteUser(id);
		
		return "redirect:/users";
	}
	
}
